package com.niit.maxandmin;

import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

public class MaxAndMinReducer extends Reducer<MaxAndMinValue, NullWritable,NullWritable,MaxAndMinValue> {

    private  long min;
    private  long max;
    private  int total;

    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        min = Long.MIN_VALUE;
        max = Long.MAX_VALUE;
        total = 0;
    }

    @Override
    protected void reduce(MaxAndMinValue key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException {
        if (key.getMin().get() < max){
            max = key.getMin().get();
        }
        if (key.getMax().get() > min){
            min = key.getMax().get();
        }
        total +=key.getTotal().get();
    }

    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        MaxAndMinValue maxAndMinValue = new MaxAndMinValue(min,max,total);
        context.write(NullWritable.get(),maxAndMinValue);
    }
}



